//
//  HMOAuthViewController.swift
//  Weibo
//
//  Created by teacher on 2017/6/5.
//  Copyright © 2017年 teacher. All rights reserved.
//

import UIKit
import SVProgressHUD

//  唯一应用id
let AppKey = "903524213"
//  App秘钥
let AppSecret = "21248b2959afb9a62c3ca31ebdedfd5b"
//  授权回调地址，用于拼接授权码
let Redirect_Uri = "http://www.itcast.cn"

//  第三方登录界面
class HMOAuthViewController: UIViewController {

    //  MARK:   --懒加载控件
    private lazy var webView: UIWebView = UIWebView()
    
    //  重写load，自定义视图
    override func loadView() {
        //  设置代理
        webView.delegate = self
        view = webView
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        requestOAuthLogin()
        setupNavUI()
    }
    
    //  加载第三方登录界面
    private func requestOAuthLogin() {
        //  请求登录地址
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(Redirect_Uri)"
        print(urlStr)
        let urlRequest = URLRequest(url: URL(string: urlStr)!)
        webView.loadRequest(urlRequest)
    }
    
    //  设置导航栏按钮
    private func setupNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        navigationItem.title = "微博登录"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFillAction))
    }
    
    //  MARK:   -- 取消按钮点击事件
    @objc private func cancelAction() {
        self.dismiss(animated: true, completion: nil)
    }

    //  MARK:   -- 自动填充按钮点击事件
    @objc private func autoFillAction() {
        //  执行js代码
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = 'hao123guohaibin@163.com';document.getElementById('passwd').value = 'guohaibin123';")
    }
}

//  MARK:   --UIWebViewDelegate
extension HMOAuthViewController: UIWebViewDelegate {
    
    //  将要开始加载请求
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if request.url?.absoluteString.hasPrefix(Redirect_Uri) == true {
            //  表示以回调页开头
            //获取判断是否有code参数
            if let query = request.url?.query, query.hasPrefix("code=") {
                //  有参数并且参数以code打头
                //  截取code参数
                let code = query.substring(from: "code=".endIndex)
//                requestAccessToken(code: code)
                HMUserAccountViewModel.sharedViewModel.requestAccessToken(code: code, callBack: { (isSuccess: Bool) in
                    if isSuccess {
                        print("登录成功")
                        //  切换到欢迎页面
                        self.dismiss(animated: false, completion: {
                            //  一定需要注意： 当前控制器完全dismis后发送切换跟视图控制器的通知，否则（父视图）控制器释放不了
                            NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotificationName), object: self)
                            
                        })
                        
                        
                    } else {
                        print("登录失败")
                    }
                })
            } else {
                //  取消授权
                dismiss(animated: true, completion: nil)
            }
            
            //  不加载
            return false
            
        }
        //  true表示加载这个请求，false不加载
        return true
    }

    
    //  开始加载
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    //  加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //  加载失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    
}

